package com.yanggu.spark.core.rdd.transform.value

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

//大数据经典的wordCount
object RDD01_WordCount {

  def main(args: Array[String]): Unit = {

    //获取环境
    val conf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("WordCount")

    //获取上下文
    val sc: SparkContext = new SparkContext(conf)

    //读取每一行
    val lines: RDD[String] = sc.textFile("input/word.txt")

    //扁平化，将每行数据拆分成单个词（自定义业务逻辑）
    val words: RDD[String] = lines.flatMap(_.split(" "))

    //这里其实可以简化flatMap的时候可以直接转换成(java, 1)元祖的形式

    //结构转换，对每个词获得初始词频
    val wordToOne: RDD[(String, Int)] = words.map((_, 1))

    //词频计数
    val wordToSum: RDD[(String, Int)] = wordToOne.reduceByKey(_ + _)

    //数据输出。按照词频降序排序
    val result: Array[(String, Int)] = wordToSum.sortBy(_._2, ascending = false).collect()

    //打印
    result.foreach(println)

    //关闭上下文
    sc.stop()
  }

}
